﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Forms;
using ClassLibrary;
using Forms.UserControls;
using Sunny.UI;
using ClassLibrary.Service;
using Forms.UserController;
using System.Diagnostics;

namespace MainForm
{

    public partial class DemandForm : UIForm
    {
        User me;
        Image senderImage;
        bool ifCreateDemmand;

        //初始化每一个需求的属性
        public string DemmandId;
        public string DemmandStatus;
        public string DemmandDate;
        public string DemmandAddr;
        public string DemmandType;
        public string DemmandDeadline;

        //不需要接收者，只需要把需求发布出
        public DemandForm(User me)
        {
            SetStyle(
                ControlStyles.UserPaint//使用自定义的绘制方式
                | ControlStyles.ResizeRedraw//当控件大小发生变化时就重新绘制
                | ControlStyles.DoubleBuffer// 双缓冲
                | ControlStyles.SupportsTransparentBackColor//则控件接受 alpha 组件数小于 255 个的 BackColor 来模拟透明度
                | ControlStyles.AllPaintingInWmPaint//禁止擦除背景.则控件忽略窗口消息 WM_ERASEBKGND 以减少闪烁
                | ControlStyles.EnableNotifyMessage// 
                                                   // Enable the OnNotifyMessage event so we get a chance to filter out 
                                                   // Windows messages before they get to the form's WndProc
                | ControlStyles.OptimizedDoubleBuffer//则控件将首先绘制到缓冲区而不是直接绘制到屏幕，这可以减少闪烁
                , true);

            InitializeComponent();
            ifCreateDemmand = false;
            panelMessage.AutoScroll = true;
            this.me = me;
            senderImage = ImageService.BytesToImage(ImageService.getProfileByID(me.UserID));

            // 手动订阅加载事件
            this.Load += UC_MessageContainer_Load;
            Color userColor = MainForm.userColor;
            UIStyles.InitColorful(userColor, Color.White);
        }



        #region 实现发送需求

        /// <summary>
        /// 当前消息气泡起始位置
        /// </summary>
        private int _top = 0;

        /// <summary>
        /// 当前消息气泡高度
        /// </summary>
        private int _height = 0;

        /// <summary>
        /// 显示接收消息
        /// </summary>
        /// <param name="content"></param>
        private void ShowReceiveMessage(Demmand demmand)
        {
            //创建一个自定义的消息显示控件
            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Receive,
                senderImage = senderImage,
                receiverImage = ImageService.BytesToImage(ImageService.getProfileByID(demmand.UserID))
            };
            item.SetInteractionContent(demmand.DemmandContent);
            item.islblContentClick(true);
            item.lblContent.Click += (sender, e) =>
            {
                DemmandDetail demmandDetail = new DemmandDetail(me, demmand);
                demmandDetail.Show();
            };

            //计算高度
            item.Top = _top + _height;
            item.Left = 15;

            _top = item.Top;
            _height = item.HEIGHT;

            //滚动条移动最上方，重新计算气泡在panel的位置
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        /// <summary>
        /// 更新界面，显示发送消息
        /// </summary>
        private async void AddSendMessage(string content)
        {
            #region 发送消息持久化
            //创建一个需求对象
            Demmand input = new Demmand(DemmandId, DemmandAddr, DemandInput.Text, DemmandType, "未完成", DateTime.Now, DemmandDeadline, me.UserID);

            DemmandService demmandService = new DemmandService();
            demmandService.AddDemmand(input);
            #endregion

            #region 追加气泡

            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Send,
                senderImage = senderImage,
                receiverImage = null
            };
            item.SetInteractionContent(content);
            item.islblContentClick(true);
            item.lblContent.Click += (sender, e) =>
            {
                DemmandDetail demmandDetail = new DemmandDetail(me, input);
                demmandDetail.Show();
            };

            item.Top = _top + _height;
            item.Left = this.Width - 92 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);

            #endregion
        }

        /// <summary>
        /// 更新界面，初始化显示发送消息
        /// </summary>
        private void ShowSendMessage(Demmand demmand)
        {
            UC_MsgItem item = new UC_MsgItem
            {
                messageType = UC_MsgItem.MessageType.Send,
                senderImage = senderImage,
                receiverImage = null
            };
            item.SetInteractionContent(demmand.DemmandContent);
            item.islblContentClick(true);
            item.lblContent.Click += (sender, e) =>
            {
                DemmandDetail demmandDetail = new DemmandDetail(me, demmand);
                demmandDetail.Show();
            };

            item.Top = _top + _height;
            item.Left = this.Width - 92 - item.WIDTH;

            _top = item.Top;
            _height = item.HEIGHT;
            panelMessage.AutoScrollPosition = new Point(0, 0);
            panelMessage.Controls.Add(item);
        }

        //初始化加载需求
        private void UC_MessageContainer_Load(object sender, EventArgs e)
        {
            // 查找所有的需求
            DemmandService demmandService = new DemmandService();
            List<Demmand> demmands = demmandService.GetAllDemmand();
            // 根据 时间 属性进行排序  
            demmands.Sort((a, b) => a.DemmandDate.CompareTo(b.DemmandDate));
            var selfNumber = me.UserID;
            //遍历每个需求，并显示
            foreach (var item in demmands)
            {
                if (item.UserID.Equals(selfNumber))
                {
                    ShowSendMessage(item);
                }
                else
                {
                    ShowReceiveMessage(item);
                }
            }
        }

        private void Send_Click(object sender, EventArgs e)
        {
            if (DemandInput.Text == "" || DemandInput.Text == null || !ifCreateDemmand)
            {
                UIMessageBox.Show("请先创建需求后点击发送！");
                return;
            }
            AddSendMessage(DemandInput.Text);
            panelMessage.AutoScrollPosition = new Point(0, this._top);
            DemandInput.Clear();
            ifCreateDemmand = false;
        }

        #endregion

        private void DemandInput_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void CreatDemmand_Click(object sender, EventArgs e)
        {
            DemmandConfirm demmandConfirm = new DemmandConfirm(DemandInput.Text, me);
            demmandConfirm.ShowDialog();

            //参数绑定
            DemmandId = demmandConfirm.valueToDemmandForm.DemmandId;
            DemmandAddr = demmandConfirm.valueToDemmandForm.DemmandAddr;
            DemmandDeadline = demmandConfirm.valueToDemmandForm.DemmandDeadline;
            DemmandStatus = demmandConfirm.valueToDemmandForm.DemmandStatus;
            DemmandType = demmandConfirm.valueToDemmandForm.DemmandType;

            DemandInput.Text += $"收货地址为：{DemmandAddr} \n";
            DemandInput.Text += $"截止日期为：{DemmandDeadline}\n";
            DemandInput.Text += $"需求类型为：{DemmandType}\n";
            DemandInput.Text += $"详细需求为：";

            ifCreateDemmand = true;
        }

        // 异步方法打开地图
        private async Task OpenHtmlMapAsync(string htmlFilePath)
        {
            // 异步执行地图打开操作
            await Task.Run(() =>
            {
                ProcessStartInfo processStartInfo = new ProcessStartInfo(htmlFilePath);
                Process process = new Process();
                process.StartInfo = processStartInfo;
                process.StartInfo.UseShellExecute = true;
                process.Start();
            });
        }

        // 地图按钮点击事件处理器
        private async void Map_Click(object sender, EventArgs e)
        {
            // 相对于应用程序启动路径的相对路径
            string relativePath = @"..\..\..\Map\map.html";
            string htmlFilePath = " ";

            try
            {
                // 获取应用程序的启动路径
                string appStartupPath = AppDomain.CurrentDomain.BaseDirectory;

                // 合并启动路径和相对路径
                htmlFilePath = Path.GetFullPath(Path.Combine(appStartupPath, relativePath));

                // 调用异步方法打开地图
                await OpenHtmlMapAsync(htmlFilePath);
            }
            catch (Exception ex)
            {
                // 显示错误消息
                UIMessageBox.Show("Error opening HTML file: " + ex.Message);
            }
        }
    }
}
